package com.pb.metadata.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pb.infra.oth.util.JwtTokenConfig;
import com.pb.metadata.mapper.DataBaseManagementMapper;
import com.pb.infra.oth.entity.common.Page;
import com.pb.infra.oth.entity.common.Result;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 数据库用户管理
 * 2021/2/20
 */
@Service
public class DataBaseManagementService {

    /**
     * DAO映射对象
     */
    @Resource
    private DataBaseManagementMapper dataBaseManagementMapper;

    /**
     * jwttoken配置类
     */
    @Resource
    private JwtTokenConfig jwtTokenConfig;

    /**
     * 查询分页数据
     * @param map 查询参数
     * @param page 页码
     * @return
     */
    public Result select(Map<String, Object> map, Page page){
        if (page != null && page.getPageIndex() != null && page.getPageSize() != null) {
            PageHelper.startPage(page.getPageIndex(), page.getPageSize());
        }
        List<Map<String, Object>> list = dataBaseManagementMapper.select(map);
        return Result.ok(new PageInfo(list).getTotal(), list);
    }

    /**
     * 数据库管理新建数据
     * @param paramMap 保存数据
     * @return
     */
    public Result insert(Map<String, Object> paramMap, HttpServletRequest request){
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        paramMap.put("createUser",userId);
        paramMap.put("databaseId", UUID.randomUUID().toString().replace("-", ""));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        paramMap.put("createTime",format.format(new Date()));
        String databaseUrl=(String)paramMap.get("databaseUrl");
        databaseUrl=databaseUrl.trim();
        paramMap.put("databaseUrl",databaseUrl);
        int count=dataBaseManagementMapper.getDataBaseCountByUrl(databaseUrl);
        if(count>0){
            paramMap.put("updateUser",userId);
            paramMap.put("updateTime",format.format(new Date()));
            dataBaseManagementMapper.updateByUrl(paramMap);
        }else{
            dataBaseManagementMapper.insert(paramMap);
        }
        return Result.OK_EMPTY;
    }


    /**
     * 数据库管理修改
     * @return
     */
     public  Result update(Map<String, Object> paramMap, HttpServletRequest request){
         String token = request.getHeader(jwtTokenConfig.getHeader());
         Claims claims = jwtTokenConfig.getClaimByToken(token);
         String userId = (String)claims.get(jwtTokenConfig.getSub());
         paramMap.put("updateUser",userId);
         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         paramMap.put("updateTime",format.format(new Date()));
         String databaseUrl=(String)paramMap.get("databaseUrl");
         databaseUrl=databaseUrl.trim();
         paramMap.put("databaseUrl",databaseUrl);
         dataBaseManagementMapper.update(paramMap);
         return Result.OK_EMPTY;
     }

    /**
     * 获取数据库数据
     * @return
     */
     public Result getDatabaseList(){
         List<Map<String,Object>> list =dataBaseManagementMapper.getDatabaseList();
         return Result.ok(list);
     }

    /**
     * 删除数据库
     * @param list
     */
     public void delete(List<String> list){
        this.dataBaseManagementMapper.delete(list);
    }

    /**
     * 启用停用数据库
     * @param paramMap
     */
    public void startOrStop( List<Map<String,Object>> paramMap){
        for (Map<String,Object> map:paramMap){
            String str=(String) map.get("activeFlag");
            map.put("activeFlag","1".equals(str)?"0":"1");
            dataBaseManagementMapper.startOrStop(map);
        }
    }

    /**
     * 查询数据库用户
     * @param paramMap
     * @return
     */
    public Result getDbUserDataList(Map<String,Object> paramMap){
        List<Map<String, Object>> list = dataBaseManagementMapper.getDbUserDataList(paramMap);
        return Result.ok(new PageInfo(list).getTotal(), list);
    }

    /**
     * 设置数据库用户
     * @param paramList
     * @return
     */
    @Transactional
    public Result setDbUserData(List<Map<String,Object>> paramList, Map<String, Object> paraMap){
        for (int i = 0; i < paramList.size(); i++) {
            String databaseId=(String)paramList.get(i).get("databaseId");
            String databaseUserId= UUID.randomUUID().toString().replace("-", "");
            String databaseUser=(String)paramList.get(i).get("databaseUser");
            String createUser=(String)paraMap.get("createUser");
            String createTime=(String)paraMap.get("createTime");
            Integer count=dataBaseManagementMapper.getCount(databaseId,databaseUser);
            if (count==0){
                dataBaseManagementMapper.setDbUserData(databaseId,databaseUserId,databaseUser,createUser,createTime);
            }
        }
        return Result.OK_EMPTY;
    }


    /**
     * 删除数据库用户
     * @param paramList
     * @return
     */
    @Transactional
    public Result delDbUserData(List<Map<String,Object>> paramList){
        for (int i = 0; i < paramList.size(); i++) {
            String databaseId=(String)paramList.get(i).get("databaseId");
            String databaseUser=(String)paramList.get(i).get("databaseUser");
            dataBaseManagementMapper.delDbUserData(databaseId,databaseUser);
        }
        return Result.OK_EMPTY;
    }
}
